package cn.fldong.service.impl;

import cn.fldong.dao.ScoreDAO;
import cn.fldong.dao.impl.ScoreDAOImpl;
import cn.fldong.model.Score;
import cn.fldong.service.ScoreService;
import java.sql.SQLException;
import java.util.List;
import java.math.BigDecimal;
import java.util.Date;

/**
 * ScoreService接口的实现类，提供成绩相关的业务逻辑实现
 */
public class ScoreServiceImpl implements ScoreService {
    private ScoreDAO scoreDAO = new ScoreDAOImpl();

    @Override
    public Score getScoreById(String scoreId) throws SQLException {
        return scoreDAO.getScoreById(scoreId);
    }

    @Override
    public List<Score> getScoresByStudentId(String studentId) throws SQLException {
        return scoreDAO.getScoresByStudentId(studentId);
    }

    @Override
    public List<Score> getScoresByCourseId(String courseId) throws SQLException {
        return scoreDAO.getScoresByCourseId(courseId);
    }

    @Override
    public Score getScoreByStudentAndCourse(String studentId, String courseId) throws SQLException {
        return scoreDAO.getScoreByStudentAndCourse(studentId, courseId);
    }

    @Override
    public List<Score> getAllScores() throws SQLException {
        return scoreDAO.getAllScores();
    }

    @Override
    public boolean addScore(Score score) throws SQLException {
        // 检查该学生该课程是否已存在成绩
        if (scoreExists(score.getStudentId(), score.getCourseId())) {
            return false;
        }

        // 计算成绩等级
        score.setGrade(calculateGrade(score.getScore()));

        return scoreDAO.addScore(score);
    }

    @Override
    public boolean updateScore(Score score) throws SQLException {
        // 计算成绩等级
        score.setGrade(calculateGrade(score.getScore()));
        return scoreDAO.updateScore(score);
    }

    @Override
    public boolean deleteScore(String scoreId) throws SQLException {
        return scoreDAO.deleteScore(scoreId);
    }

    @Override
    public boolean scoreExists(String studentId, String courseId) throws SQLException {
        return scoreDAO.scoreExists(studentId, courseId);
    }

    @Override
    public String calculateGrade(BigDecimal scoreValue) {
        if (scoreValue == null) {
            return "F";
        }
        double score = scoreValue.doubleValue();
        if (score >= 90) {
            return "A";
        } else if (score >= 80) {
            return "B";
        } else if (score >= 70) {
            return "C";
        } else if (score >= 60) {
            return "D";
        } else {
            return "F";
        }
    }
}